/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.webview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.dataoke.shoppingguide.app773026.util.AppUtil;

import org.json.JSONException;
import org.json.JSONObject;
/**
 *
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class BaseWebViewClient extends WebViewClient {
    protected Activity context;
    private String lastDetailUrl;
    private int scrollY;

    public BaseWebViewClient(Activity context) {
        this.context = context;
    }

    public WebResourceResponse shouldInterceptRequest(WebView view,
                                                      WebResourceRequest request) {
        return super.shouldInterceptRequest(view, request);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        String url = request.getUrl().toString();
        if(url.contains("taobao.com") || url.contains("tb.cn")) {
            AppUtil.openTaoBaoApp(this.context, url);
        }
        else if(url.contains("jd.com") || url.startsWith("openapp.jdmobile://")) {
            try {
                openJingDongApp(view, url);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        else if(url.contains("pinduoduo.com")) {
            openPinDuoDuoApp(view, url);
        }
        else if(url.contains("vip.com") || url.contains("vipshop://")) {
            openVipApp(view, url);
        }
        else if(url.startsWith("snssdk1128://")) {
            openDouYinApp(url);
        }
        else {
            if(url.startsWith("http") || url.startsWith("https")) {
                view.loadUrl(url);//调用webview本身的loadUrl方法
            }

        }

        return true;

    }

    public void setScrollY(int scrollY) {
        this.scrollY = scrollY;
    }

    @Override
    public void onLoadResource(WebView view, String url) {
        super.onLoadResource(view, url);
        if(url.contains("itemInfo?id=")
                || url.contains("detail?product_ids=")
                || url.contains("item/index?id=")
                || url.contains("item/indexRec?id=")) {

//            String id = readValueFromUrlStrByParamName(url, "id");
//            Intent intent = new Intent(context, ProductDetailActivity.class);
//            intent.putExtra(PRODUCT_ID_KEY, id);
//            context.startActivity(intent);
            if(lastDetailUrl != null) {
                BrowserDetailActivity.show(context, lastDetailUrl);
            }

        }
//        if(url.startsWith("https://img.alicdn.com")){
//            scrollY = view.getScrollY();
//        }
        view.loadUrl(loadJs());
    }

    String clickUrl;
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        clickUrl = url;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        view.loadUrl(loadJs());
        if(url.contains("detail?id=")) {
            lastDetailUrl = url;
            view.setVisibility(View.INVISIBLE);
            if(clickUrl != null) {
                view.loadUrl(clickUrl);
            }

            new Handler().postDelayed(() -> {
                view.setVisibility(View.VISIBLE);
                if(scrollY > 0) {
                    view.scrollTo(0, scrollY);
                }
            },1500);

        }
//        if(url.startsWith("https://s.tb.cn") && lastDetailUrl != null) {
//            view.loadUrl(lastDetailUrl);
//            lastDetailUrl = null;
//        }

    }

    protected String loadJs() {
//        StringBuilder sb = new StringBuilder();
//        sb.append("var newscript = document.createElement(\"script\");");
//        sb.append("document.getElementsByClassName('footer')[0].style.display='none';");
//        sb.append("document.getElementsByClassName('detail-footer-wrap')[0].style.display='none';");
//
//        sb.append("document.body.appendChild(newscript);");
//
//        return sb.toString();
        return "javascript:(function(){" +
                "var footers=document.getElementsByClassName('footer');" +
                "if(footers.length>0){" +
                "footers[0].style.display='none';" +
                "}" +
                "var backBtn=document.getElementsByClassName('back-btn g-df-c');" +
                "if(backBtn.length>0){" +
                "backBtn[0].style.display='none';" +
                "}" +
                "var homeBtn=document.getElementsByClassName('home-btn g-df-c');" +
                "if(homeBtn.length>0){" +
                "homeBtn[0].style.display='none';" +
                "}" +
                "var topNavBacks=document.getElementsByClassName('nav-back');" +
                "for(let i=0; i<topNavBacks.length; i++){" +
                "topNavBacks[i].style.display='none';" +
                "}" +
                "var pageBacks=document.getElementsByClassName('iconfont hdk-jiantou back-btn');" +
                "for(let i=0; i<pageBacks.length; i++){" +
                "pageBacks[i].style.display='none';" +
                "}" +
                "var page2Backs=document.getElementsByClassName('page-back');" +
                "for(let i=0; i<page2Backs.length; i++){" +
                "page2Backs[i].style.width='3rem';" +
                "}" +
                "})();";
    }

    /**
     * @param urlStr    url字符串。
     * @param paramName 指定参数名称。
     * @return NA.
     * @desc 获取url中指定参数的值。
     */
    public static String readValueFromUrlStrByParamName(String urlStr, String paramName) {
        if (urlStr != null && urlStr.length() > 0) {
            int index = urlStr.indexOf("?");
            String temp = (index >= 0 ? urlStr.substring(index + 1) : urlStr);
            String[] keyValue = temp.split("&");
            String destPrefix = paramName + "=";
            for (String str : keyValue) {
                if (str.indexOf(destPrefix) == 0) {
                    return str.substring(destPrefix.length());
                }
            }
        }
        return null;
    }
    public void openDouYinApp(String url) {
        if (checkPackage(context, "com.ss.android.ugc.aweme")) {
            Intent intent = new Intent();
            Uri uri = Uri.parse(url);
            intent.setData(uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }else {
            Toast.makeText(context, "未安装抖音APP", Toast.LENGTH_SHORT).show();
        }
    }

    public void openJingDongApp(WebView view, String url) throws JSONException {
        if (checkPackage(context, "com.jingdong.app.mall")) {
//            url = "openapp.jdmobile://virtual?params=%7B%22sourceValue%22:%220_productDetail_97%22,%22des%22:%22productDetail%22,%22skuId%22:%22"+id+"%22,%22category%22:%22jump%22,%22sourceType%22:%22PCUBE_CHANNEL%22%7D";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("category", "jump");
            jsonObject.put("des", "getCoupon");
            jsonObject.put("url", url);

            url = "openapp.jdmobile://virtual?params=" + jsonObject.toString();
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri uri = Uri.parse(url);
            intent.setData(uri);
            context.startActivity(intent);
        }else {
            if(url.startsWith("openapp.jdmobile://")) {
                Toast.makeText(context, "未安装京东APP", Toast.LENGTH_SHORT).show();
            } else {
                view.loadUrl(url);
            }

        }
    }

    public void openPinDuoDuoApp(WebView view, String url) {
        if (checkPackage(context, "com.xunmeng.pinduoduo")) {
            if (url.startsWith("https://mobile.yangkeduo.com/app.html?launch_url=")) {
                url = url.replaceFirst("https://mobile.yangkeduo.com/app.html?launch_url=", "pinduoduo://com.xunmeng.pinduoduo/");
            }
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri uri = Uri.parse("pinduoduo://com.xunmeng.pinduoduo/" + url);
            intent.setData(uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            view.loadUrl(url);
        }
    }

    public void openVipApp(WebView view, String url){
        if (checkPackage(context, "com.achievo.vipshop")) {
            if(url.startsWith("vipshop://")) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri uri = Uri.parse(url);
                intent.setData(uri);
                context.startActivity(intent);
            } else {
                view.loadUrl(url);
            }
        } else {
            if(url.startsWith("http")) {
                view.loadUrl(url);
            }

        }
    }
    public static boolean checkPackage(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            context.getPackageManager().getApplicationInfo(packageName, PackageManager
                    .MATCH_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }

    }
}
